package homework2;

import java.util.*;

/**
 * 作业二：编程获取两个指定字符串中的最大相同子串。
 * 如： s1="asdafghjka", s2="aaasdfg" 他们的最大子串为"asd"
 * 提示： 将短的那个串进行长度依次递减的子串与较长的串比较
 */
public class SubStringMax {
    private String string1;
    private String string2;

    public SubStringMax() {
    }

    public SubStringMax(String string1, String string2) {
        setString1(string1);
        setString2(string2);
    }

    public String getString1() {
        return string1;
    }

    public void setString1(String string1) {
        this.string1 = string1;
    }

    public String getString2() {
        return string2;
    }

    public void setString2(String string2) {
        this.string2 = string2;
    }

    public void subString() {
        int num1 = string1.length();
        int num2 = string2.length();
        //存放字符串子串及长度的键值对
        Map<String, Integer> stringIntegerMap;
        //判断哪个字符串比较短
        if (num1 <= num2) {
            stringIntegerMap = maxSubString(string2, string1);
        } else {
            stringIntegerMap = maxSubString(string1, string2);
        }
        //取出子串字符串
        Set<String> values = stringIntegerMap.keySet();
        //取出子串长度
        Collection<Integer> values1 = stringIntegerMap.values();
        //获取最长的子串长度
        Integer max = Collections.max(values1);
        //长出最长子串的字符串并打印
        for (String value : values) {
            if (value.length() == max) {
                System.out.println("最大的子串是：" + value);
            }
        }
    }

    private Map<String, Integer> maxSubString(String big, String small) {
        int num2 = small.length();
        //存放子串和长度
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < num2; i++) {
            for (int j = num2; j > i; j--) {
                String substring = small.substring(i, j);
                System.out.println(substring);
                if (big.contains(substring)) {
                    map.put(substring, substring.length());
                }
            }
        }
        return map;
    }
}
